
library basicnetservice;
import 'dart:io';

import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/service/net_service.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/logs.dart';

import '../../../../main.dart';
import 'app_api.dart';

// String kBasicUrl

class AppNetService extends NetService {

  AppNetService();

  @override
  request(String url,
          {Method? method, Map<String, dynamic>? params, var file, String? fileName,
          String? fileSavePath, BuildContext? context, bool showLoad = false, bool showLog = true}) async {
    /// 传参进行统一处理, 加上基本参数
    Map<String, dynamic> basicParam = await getBasicParam();
    // basicParam["timeStamp"] = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
    // basicParam["token"] = LocalStorage.getToken();
    //
    // final languageValue = LocalStorage.getLanguageValue();
    // basicParam["langType"] = languageValue == 3 ? "en" : "hk";

    if (params != null) {
      basicParam.addAll(params);
    }

    ResultData resultData = await super.request(url, method: method, params: basicParam, file: file,
                                                fileName: fileName,
                                                fileSavePath: fileSavePath,
                                                showLog: showLog,
                                                );

    /// 当apiToken 过期或者错误时的提示码
    // if ("0" == resultData.code && context != null) {
    //   // 退出登录并跳转到登录界面
    //   // App.navigateTo(context, QuRoutes.ROUTE_MINE_LOGIN, clearStack: true);
    // }


    SmartDialog.dismiss();
    if(resultData.response == null) {
      return null;
    }
    final code = resultData.response!["code"];

    // logs("code: $code");
    if(code == 1001) {  // 未经授权, 参数错误, 登录失效, 重新授权
      if(Get.currentRoute != LCRouter.login) {
        Get.offNamed(LCRouter.login);
        // AppApi.getInstance().startLogout();
      }

      // final title = ModalRoute.of(navigatorKey.currentState.context).settings.name;
      // if(title != "/"){    // 非根路由
      //   LocalStorage.clearAllData();
      //   Future.delayed(Duration(milliseconds: 500), () {   // 此处需要延迟调用
      //     Navigator.of(context).pushNamedAndRemoveUntil(LCRouter.root, (route) {
      //       return false;
      //     });
      //   });
      // }

      return resultData;
    }else if(code == 400) {  // 请求参数与后台不一致
      Fluttertoast.showToast(msg: "400: 请求参数与后台不一致");
      return null;
    } else {
      return resultData;
    }

    return resultData;
  }

  @override
  getBasicUrl() {
    final defaultUrl = "http://www.williams-conetchill.com";  // http://williams.benwuyou.cn
    const defaultUrl_local = "http://williams.benwuyou.cn";   // 192.168.0.115:8081   192.168.0.7
    // LocalStorage.getIsLogin()
    return defaultUrl;
  }

  @override
  getHeaders() async{

    Map<String, dynamic>? headers; // = {'Authorization': 'Basic cGlnOnBpZw=='};

    final token = LocalStorage.getToken();
    if(token.isNotEmpty){
      headers = {'token': token};  // Bearer
    }
    return headers;
  }

  // 基础参数
  Future<Map<String, dynamic>> getBasicParam() async {
    Map<String, dynamic> basicParam = {};
    // basicParam["agent"] = Platform.isAndroid ? "android" : "ios";
    return basicParam;
  }
}
